Adding Indexes and Constraints to a Database in Vapor

DDL definitions for model classes are to be done in Migration extension.

There is a prepare function for that purpose.


Add Index to a field

extension Season : Migration {
  static func prepare(on connection: PostgreSQLConnection) -> Future<Void> {
    return Database.create(self, on: connection) { builder in
      try addProperties(to: builder)
      // index to a name
      try builder.addIndex(to: \.name)
    }
  }
}

Add index and a UNIQUE Constraint

extension Season : Migration {
  static func prepare(on connection: PostgreSQLConnection) -> Future<Void> {
    return Database.create(self, on: connection) { builder in
      try addProperties(to: builder)
      // index to a name with a UNIQUE constraint
      try builder.addIndex(to: \.name, isUnique: true)
    }
  }
}

Add the model to a database

In the configure.swift add the migration for a new table for our model:

  var migrations = MigrationConfig()
  migrations.add(model: Tip.self, database: .psql)
  migrations.add(model: Season.self, database: .psql)
  services.register(migrations)

Prev: Database Relationships

Next: Adding Foreign Keys to a Database in Vapor


Vapor 3 Tutorial Start


#pub #vapor #postgresql #ddl #one-to-many #many-to-one #migration